package cn.edu.tju.elm.service;

import cn.edu.tju.core.model.User;
import cn.edu.tju.core.security.service.UserService;
import cn.edu.tju.elm.exception.DataNotFoundException;
import cn.edu.tju.elm.exception.ForbiddenException;
import cn.edu.tju.elm.exception.MethodArgumentNotValidException;
import cn.edu.tju.elm.model.DTO.FoodDTO;
import cn.edu.tju.elm.model.entity.Business;
import cn.edu.tju.elm.model.entity.Food;
import cn.edu.tju.elm.repository.BusinessRepository;
import cn.edu.tju.elm.repository.FoodRepository;
import cn.edu.tju.elm.repository.OrderDetailetRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class FoodService {
    private final FoodRepository foodRepository;
    private final BusinessRepository businessRepository;
    private final OrderDetailetRepository orderDetailetRepository;
    private final UserService userService;

    public FoodService(FoodRepository foodRepository, BusinessRepository businessRepository, OrderDetailetRepository orderDetailetRepository, UserService userService) {
        this.foodRepository = foodRepository;
        this.businessRepository = businessRepository;
        this.orderDetailetRepository = orderDetailetRepository;
        this.userService = userService;
    }

    public Food getFoodById(Long id) {
        Food existingFood = foodRepository.findById(id)
                .orElseThrow(() -> new DataNotFoundException("资源未找到：店铺不存在"));;
        return existingFood;
    }

    public Food addFood(Food food,Long businessId) {
        Business exBusiness = businessRepository.findById(businessId)
                .orElseThrow(()->new MethodArgumentNotValidException("请求参数非法：店铺不存在"));
        User creator = userService.getUserWithAuthorities();
        if(!creator.equals(exBusiness.getBusinessOwner())){
            throw new ForbiddenException("权限不足：仅可为当前用户所拥有的店铺添加商品");
        }

        LocalDateTime now = LocalDateTime.now();

        Food newFood = Food.builder()
                .foodExplain(food.getFoodExplain())
                .foodImg(food.getFoodImg())
                .foodName(food.getFoodName())
                .foodPrice(food.getFoodPrice())
                .business(exBusiness)
                .remarks(food.getRemarks())
                .build();

        newFood.setCreateTime(now);
        newFood.setCreator(creator.getId());
        newFood.setUpdateTime(now);
        newFood.setUpdater(creator.getId());
        newFood.setDeleted(false);

        return foodRepository.save(newFood);
    }
    public Food addFood2(Food food) {

        Business business = businessRepository.findById(food.getBusiness().getId())
                .orElseThrow(()->new MethodArgumentNotValidException("请求参数非法：店铺不存在"));

        LocalDateTime now = LocalDateTime.now();

        Food newFood = Food.builder()
                .foodName(food.getFoodName())
                .foodPrice(food.getFoodPrice())
                .business(business)
                .build();

        newFood.setCreateTime(now);
//        newFood.setCreator(creator.getId());
        newFood.setUpdateTime(now);
//        newFood.setUpdater(creator.getId());
        newFood.setDeleted(false);

        return foodRepository.save(newFood);
    }

//    public List<Food> listAllFoods() {
//        List<Food> existingFood = foodRepository.findAll();
//        if(existingFood.isEmpty()){
//            throw(new DataNotFoundException("资源未找到：暂无商品"));
//        }else{
//            return existingFood;
//        }
//    }
//
//    public List<Food> findFoodsByOrder(Long orderId) {
//        return orderDetailetRepository.findFoodsByOrderId(orderId);
//    }
//
//    public List<Food> findFoodsByBusiness(Long businessId) {
//        return foodRepository.findAllByBusiness(businessRepository.findById(businessId).
//                orElseThrow(() -> new MethodArgumentNotValidException("请求参数非法：店铺不存在")));
//    }
//
//    public List<Food> findFoodsByBusiness(Long businessId, Long orderId) {
//        Business existingBusiness = businessRepository.findById(businessId).
//                orElseThrow(() -> new MethodArgumentNotValidException("请求参数非法：店铺不存在"));
//        if(!Objects.equals(existingBusiness.getId(), businessId)){
//            throw new MethodArgumentNotValidException("请求参数非法：店铺不一致");
//        }
//        return foodRepository.findAllByBusiness(existingBusiness);
//    }

    public Food updateFood(Long id, FoodDTO foodDTO) {
        Food existingFood = foodRepository.findById(id)
                .orElseThrow(() -> new MethodArgumentNotValidException("请求参数非法：商品不存在"));

        User nowUser = userService.getUserWithAuthorities();
        User existingUser = existingFood.getBusiness().getBusinessOwner();
        if(!existingUser.equals(nowUser)){
            throw new ForbiddenException("权限不足：用户非店铺所有者");
        }
        BeanUtils.copyProperties(foodDTO,existingFood);

        LocalDateTime now = LocalDateTime.now();
        existingFood.setUpdateTime(now);
        existingFood.setUpdater(nowUser.getId());

        // 3. 调用 save()（此时 existingUser 是 managed 状态，save() 触发 UPDATE）
        return foodRepository.save(existingFood);
    }

    public List<Food> listFoodByBusiness(Long businessId) {
        Business business =businessRepository.findById(businessId)
                .orElseThrow(()-> new MethodArgumentNotValidException("请求参数非法：店铺不存在"));
        return foodRepository.findAllByBusiness(business);
    }

    public Food deleteFoodById(Long id) {
        User nowUser = userService.getUserWithAuthorities();
        Food food = foodRepository.findById(id)
                .orElseThrow(()-> new MethodArgumentNotValidException("请求参数非法：商品不存在"));
        User owner = food.getBusiness().getBusinessOwner();
        if (!nowUser.equals(owner)){
            throw new ForbiddenException("权限不足：仅可删除当前用户的商品");
        }

        food.setDeleted(true);

        return foodRepository.save(food);
    }
}
